var table = layui.table;
var uploadInst;

$(document).ready(function () {
    $("#addDirBtn").click(addDir);
    $("#editDirBtn").click(editDir);
    $("#delDirBtn").click(delDir);

    //绑定上传按钮
    uploadInst = layui.upload.render({
        elem: '#upFileBtn',
        url: '/ref/pub/upload',
        accept: 'file',
        exts: $("#fileExts").val(),
        size: $("#fileSize").val(),
        auto: false,
        choose: function(obj) {
            upload(obj);
        },
        done: function(res){
            uploadSuccess(res);
        },
        error: function(){
            //请求异常回调
        }
    });

    var setting = {
        view: {
            dblClickExpand: false,
            showLine: true,
            // showIcon: false,
            selectedMulti: false
        },
        data: {
            key: {
                name: 'dirName',
                url: 'xurl'
            },
            simpleData: {
                enable: true,
                idKey: 'id',
                pIdKey: 'pid',
                rootPId: 0
            },
        },
        callback: {
            onClick: zTreeOnClick
        }
    };
    $.get('/ref/pub/findAll?time=' + new Date().getTime(), function (result) {
        var tree = $.fn.zTree.init($("#tree"), setting, result.data);
        tree.expandAll(true);
    });

    //初始化数据列表
    load();

    //初始化右边工具栏
    initRightToolbar();
})

function zTreeOnClick(event, treeId, treeNode) {
    if (0 == treeNode.id) {
        $("#dirId").val("")
    } else {
        $("#dirId").val(treeNode.id)
    }
    search();
};

function addDir() {
    var tree = $.fn.zTree.getZTreeObj("tree");
    if (0 != tree.getSelectedNodes().length) {
        var node = tree.getSelectedNodes()[0];
        layer.prompt({title: '目录名称'}, function (input, index) {
            $.post('/ref/pub/addDir', {id: node.id, childName: input}, function (result) {
                if (200 == result.code) {
                    tree.addNodes(node, result.data);
                    layer.close(index);
                } else {
                    layer.alert(result.msg);
                }
            })
        });
    } else {
        layer.alert("请选择一个目录");
    }
}

function editDir() {
    var tree = $.fn.zTree.getZTreeObj("tree");
    if (0 != tree.getSelectedNodes().length) {
        var node = tree.getSelectedNodes()[0];
        if (0 == node.id) {
            layer.alert('不允许编辑根目录');
        } else {
            layer.prompt({title: '目录名称', value: node.dirName}, function (input, index) {
                $.post('/ref/pub/editDir', {id: node.id, newName: input}, function (result) {
                    if (200 == result.code) {
                        node.dirName = input;
                        tree.updateNode(node);
                        layer.close(index);
                    } else {
                        layer.alert(result.msg);
                    }
                })
            });
        }
    } else {
        layer.alert("请选择一个目录");
    }
}

function delDir() {
    var tree = $.fn.zTree.getZTreeObj("tree");
    if (0 != tree.getSelectedNodes().length) {
        layer.confirm('删除目录将同时删除目录下的所有文件，确定删除吗？', function (index) {
            var node = tree.getSelectedNodes()[0];
            var ids = getChildrenNode(node, node.id);
            if (0 == node.id) {
                ids = ids.substring(2);
            }
            $.post('/ref/pub/delDir', {ids: ids}, function (result) {
                if (200 == result.code) {
                    if (0 == node.id) {
                        tree.removeChildNodes(node);
                    } else {
                        tree.removeNode(node);
                    }
                    layer.close(index);
                } else {
                    layer.alert("删除失败");
                }
            });
        });
    } else {
        layer.alert("请选择一个目录");
    }
}

function upload(obj) {
    var tree = $.fn.zTree.getZTreeObj("tree");
    if (0 != tree.getSelectedNodes().length) {
        uploadInst.reload({
            data: {
                dirId: $("#dirId").val()
            }
        });
        uploadInst.upload();
    } else {
        layer.alert("请选择一个目录");
    }
}

function uploadSuccess(result) {
    if (200 == result.code) {
        search();
    } else {
        layer.alert(result.msg);
    }
}

/**
 * 递归查询当前节点下的所有子节点
 * @param treeNode
 * @param result
 * @returns {*}
 */
function getChildrenNode(treeNode, result) {
    if (treeNode.isParent) {
        var childrenNodes = treeNode.children;
        if (childrenNodes) {
            //子节点拼接
            for (var i = 0; i < childrenNodes.length; i++) {
                result += ',' + childrenNodes[i].id;
                result = getChildrenNode(childrenNodes[i], result);
            }
        }
    }
    return result;
}

function load() {
    table.render({
        id: 'dataTable',
        elem: '#dataTable',
        method: 'post',
        url: '/ref/pub/findList',
        response: {
            statusCode: 200
        },
        cols: [[
            {field: 'id', title: 'ID', sort: true, hide: true},
            {field: 'fileName', title: '文件名', sort: true},
            {field: 'suffix', title: '格式', sort: true},
            {field: 'fileSizeStr', title: '大小', sort: true},
            {field: 'dirNameStr', title: '目录', sort: true},
            {field: 'createName', title: '上传人', sort: true},
            {field: 'createTime', title: '上传时间', sort: true},
            {field: 'note', title: '备注', sort: true},
            {fixed: 'right', width: 190, align: 'center', unresize: true, toolbar: '#rightToolbar'}
        ]],
        page: true
    });

    $("#searchBtn").click(search);

    layui.laydate.render({
        elem: '#search_create_time',
        trigger: 'click'
    });
}

function initRightToolbar() {
    table.on('tool(dataTable)', function (obj) {
        if (obj.event === 'edit') {
            edit(obj);
        } else if (obj.event === 'del') {
            del(obj);
        } else if (obj.event === 'down') {
            down(obj);
        }
    });
}

/**
 * 修改备注按钮
 * @param obj
 */
function edit(obj) {
    layer.prompt({title: '备注', value: obj.data.note}, function (input, index) {
        $.post('/ref/pub/editNote', {id: obj.data.id, note: input}, function (result) {
            if (200 == result.code) {
                $(".layui-laypage-btn")[0].click();
                layer.close(index);
            } else {
                layer.alert(result.msg);
            }
        })
    });
}

/**
 * 删除按钮
 * @param obj
 */
function del(obj) {
    layer.confirm('确定删除数据吗？', function(index){
        $.get("/ref/pub/delFile/" + obj.data.id, function(result) {
            if (200 == result.code) {
                layer.close(index);
                table.reload('dataTable');
            } else {
                layer.alert("删除失败");
            }
        });
    });
}

/**
 * 下载按钮
 * @param obj
 */
function down(obj) {
    window.location = "/ref/pub/downFile/" + obj.data.id;
}

/**
 * 查询按钮
 */
function search() {
    table.reload('dataTable', {
        page: {
            curr: 1
        },
        where: {
            dirId: $("#dirId").val(),
            fileName: $("#search_file_name").val(),
            createName: $("#search_create_name").val(),
            createTime: $("#search_create_time").val()
        }
    });
}